<template>
	<view class="teacherSick">
		<!-- 搜索学生的姓名 -->
		<view class="searchStudent">
			<uni-search-bar 
			    :radius="100" 
				@confirm="search" 
				placeholder="请输入要查询的学生姓名" 
				v-model="searchValue"
				@clear="loadData()"
				@blur="loadData()"
				@cancel="loadData()"
			></uni-search-bar>
		</view>
		<view class="content">
			<!-- 切换 -->
			<view class="changetitle">
	        	<uni-segmented-control
	        	    :current="current"
	        		:values="item"
	        		activeColor='#007aff'
		    		@clickItem="onClickItem"
	        	></uni-segmented-control>
	        </view>
	        <view class="detailcontent">
				<!-- 待审核部分 -->
	        	<view class="pendingapproval" v-show="current === 0">
					<view class="pendinglist">
						<view class="item" v-for="(item ,index) in pendingRecordsList" :key="index" @click="ToteacherApproval(item)">
							<view class="left">
								<text class="itemname">姓名: {{ item.studentName }}</text>
								<text class="itemapplytime">申请时间: {{ item.applyTime.replace("T", " ")}}</text>
								<text class="itemmessage">申请理由: {{ item.message }}</text>
							</view>
							<view class="right">
								<text class="itemstatus">待审批</text>
							</view>
						</view>
					</view>
	        	</view>
				
				<view class="no-data" v-if="current === 0 && pendingRecordsList.length === 0">
					<image src="/static/images/nodata.png" class="nodata-image"></image>
				    <text>暂无待审批记录 ~</text>
				</view>
				
				<!-- 学生的全部申请 -->
	        	<view class="allapply" v-show="current === 1">
	        		<view class="pendinglist">
	        			<view class="item" v-for="(item ,index) in allRecordsList" :key="index" @click="ToteacherApproval(item)">
	        				<view class="left">
	        					<text class="itemname">姓名: {{ item.studentName }}</text>
	        					<text class="itemapplytime">申请时间: {{ item.applyTime.replace("T", " ")}}</text>
	        					<text class="itemmessage">申请理由: {{ item.message }}</text>
	        				</view>
	        				<view class="right">
	        					<text class="itemstatus" :class="item.status === 0 ? 'pending' : item.status === 1 ? 'approved' : 'rejected'">{{ item.status === 0 ? '待审批' : item.status === 1 ? '已批准' : '已驳回' }}</text>
	        				</view>
	        			</view>
	        		</view>
	        	</view>
				
				<view class="no-data" v-if="current === 1 && allRecordsList.length === 0">
					<image src="/static/images/nodata.png" class="nodata-image"></image>
				    <text>暂无申请记录 ~</text>
				</view>
				
				<view class="nomoreData" v-show="this.currentpage >= this.pages && this.total !== 0">
				    <text> — 没有更多数据 — </text>
			    </view>
	        </view>
			
			<!-- 底部分页 -->
			<uni-pagination
			    :show-icon="true"
				:current="currentpage"
				:total="total" 
				:pageSize="5"
				@change="changepage"/>
		</view>
		
        <!-- 底部导航栏 -->
        <view class="tab-bar">
          <view 
            class="tab-item" 
            :class="{active: currentTab === 0}" 
            @click="switchTab(0)"
          >
            <text class="cuIcon cuIcon-home"></text>
            <text class="tab-text">首页</text> 
          </view>
          
          <view 
            class="tab-item" 
            :class="{active: currentTab === 1}" 
            @click="switchTab(1)"
          >
            <text class="cuIcon cuIcon-form"></text>
            <text class="tab-text">申请</text>
          </view>
          
          <view 
            class="tab-item" 
            :class="{active: currentTab === 2}" 
            @click="switchTab(2)"
          >
            <text class="cuIcon cuIcon-message"></text>
            <text class="tab-text">消息</text>
          </view>
          
          <view 
            class="tab-item" 
            :class="{active: currentTab === 3}" 
            @click="switchTab(3)"
          >
            <text class="cuIcon cuIcon-my"></text>
            <text class="tab-text">我的</text>
          </view>
        </view>
	</view>
</template>

<script>
	// 模拟的全部数据
	const mockData = [
	  {
	    id: 1,
	    studentId: 20230001,
	    studentName: "张三",
	    status: 0, // 0-未审核
	    applyTime: "2023-06-10T09:00:00",
	    startTime: "2023-06-12T08:00:00",
	    endTime: "2023-06-13T18:00:00",
	    message: "感冒发烧需要休息",
	    teacherId: 1001,
	    teacherName: "王老师",
	    classId: 2301,
	    className: "计算机23级1班"
	  },
	  {
	    id: 2,
	    studentId: 20230002,
	    studentName: "李四",
	    status: 1, // 1-已批准
	    applyTime: "2023-06-11T10:30:00",
	    startTime: "2023-06-13T08:00:00",
	    endTime: "2023-06-14T18:00:00",
	    message: "参加编程比赛",
	    teacherId: 1001,
	    teacherName: "王老师",
	    classId: 2301,
	    className: "计算机23级1班"
	  },
	  {
	    id: 3,
	    studentId: 20230003,
	    studentName: "王五",
	    status: 2, // 2-已驳回
	    applyTime: "2023-06-12T14:15:00",
	    startTime: "2023-06-15T08:00:00",
	    endTime: "2023-06-16T18:00:00",
	    message: "回家探亲",
	    teacherId: 1001,
	    teacherName: "王老师",
	    classId: 2301,
	    className: "计算机23级1班",
	    rejectReason: "非紧急事由不予批准" // 驳回原因
	  },
	  {
	    id: 4,
	    studentId: 20230004,
	    studentName: "赵六",
	    status: 0,
	    applyTime: "2023-06-13T11:20:00",
	    startTime: "2023-06-16T08:00:00",
	    endTime: "2023-06-17T18:00:00",
	    message: "牙科手术",
	    teacherId: 1001,
	    teacherName: "王老师",
	    classId: 2301,
	    className: "计算机23级1班"
	  },
	  {
	    id: 5,
	    studentId: 20230005,
	    studentName: "钱七",
	    status: 1,
	    applyTime: "2023-06-14T16:45:00",
	    startTime: "2023-06-18T08:00:00",
	    endTime: "2023-06-19T18:00:00",
	    message: "参加学术会议",
	    teacherId: 1001,
	    teacherName: "王老师",
	    classId: 2301,
	    className: "计算机23级1班"
	  },
	  {
	    id: 6,
	    studentId: 20230006,
	    studentName: "孙八",
	    status: 2,
	    applyTime: "2023-06-15T13:10:00",
	    startTime: "2023-06-20T08:00:00",
	    endTime: "2023-06-21T18:00:00",
	    message: "朋友婚礼",
	    teacherId: 1001,
	    teacherName: "王老师",
	    classId: 2301,
	    className: "计算机23级1班",
	    rejectReason: "个人社交活动不在批准范围"
	  },
	  {
	    id: 7,
	    studentId: 20230007,
	    studentName: "周九",
	    status: 0,
	    applyTime: "2023-06-16T09:30:00",
	    startTime: "2023-06-22T08:00:00",
	    endTime: "2023-06-23T18:00:00",
	    message: "眼部手术复查",
	    teacherId: 1001,
	    teacherName: "王老师",
	    classId: 2301,
	    className: "计算机23级1班"
	  },
	  {
	    id: 8,
	    studentId: 20230008,
	    studentName: "吴十",
	    status: 1,
	    applyTime: "2023-06-17T15:00:00",
	    startTime: "2023-06-24T08:00:00",
	    endTime: "2023-06-25T18:00:00",
	    message: "代表学校参加体育比赛",
	    teacherId: 1001,
	    teacherName: "王老师",
	    classId: 2301,
	    className: "计算机23级1班"
	  },
	  {
	    id: 9,
	    studentId: 202303010209,
	    studentName: "郑子豪",
	    status: 0,
	    applyTime: "2025-04-16T14:25:00",
	    startTime: "2025-04-17T08:30:00",
	    endTime: "2025-04-19T17:00:00",
	    message: "身体不适，需去医院检查",
	    teacherId: 101,
	    teacherName: "李建国",
	    classId: 230101,
	    className: "计算机学院 23 级软件工程 1 班"
	  },
	  {
	    id: 10,
	    studentId: 202303010210,
	    studentName: "徐若曦",
	    status: 2,
	    applyTime: "2025-04-20T10:10:00",
	    startTime: "2025-04-21T09:00:00",
	    endTime: "2025-04-23T15:00:00",
	    message: "处理个人重要事务",
	    teacherId: 101,
	    teacherName: "李建国",
	    classId: 230101,
	    className: "计算机学院 23 级软件工程 1 班"
	  },
	  {
	    id: 11,
	    studentId: 202303010211,
	    studentName: "孙嘉豪",
	    status: 1,
	    applyTime: "2025-03-07T12:30:00",
	    startTime: "2025-03-09T08:00:00",
	    endTime: "2025-03-10T16:00:00",
	    message: "参加学校体育比赛",
	    teacherId: 101,
	    teacherName: "李建国",
	    classId: 230101,
	    className: "计算机学院 23 级软件工程 1 班"
	  },
	  {
	    id: 12,
	    studentId: 202303010212,
	    studentName: "林悦心",
	    status: 0,
	    applyTime: "2025-03-13T16:40:00",
	    startTime: "2025-03-14T08:30:00",
	    endTime: "2025-03-16T17:00:00",
	    message: "突发感冒，需要休息",
	    teacherId: 101,
	    teacherName: "李建国",
	    classId: 230101,
	    className: "计算机学院 23 级软件工程 1 班"
	  },
	  {
	    id: 13,
	    studentId: 202303010213,
	    studentName: "宋逸飞",
	    status: 2,
	    applyTime: "2025-03-19T11:20:00",
	    startTime: "2025-03-20T09:00:00",
	    endTime: "2025-03-22T14:00:00",
	    message: "参加社会实践活动",
	    teacherId: 101,
	    teacherName: "李建国",
	    classId: 230101,
	    className: "计算机学院 23 级软件工程 1 班"
	  },
	  {
	    id: 14,
	    studentId: 202303010214,
	    studentName: "周诗涵",
	    status: 1,
	    applyTime: "2025-03-25T13:50:00",
	    startTime: "2025-03-27T08:00:00",
	    endTime: "2025-03-28T16:00:00",
	    message: "参加校园文化活动",
	    teacherId: 101,
	    teacherName: "李建国",
	    classId: 230101,
	    className: "计算机学院 23 级软件工程 1 班"
	  },
	  {
	    id: 15,
	    studentId: 202303010215,
	    studentName: "许铭轩",
	    status: 0,
	    applyTime: "2025-04-01T15:10:00",
	    startTime: "2025-04-02T08:30:00",
	    endTime: "2025-04-04T17:00:00",
	    message: "牙齿疼痛，需去看牙医",
	    teacherId: 101,
	    teacherName: "李建国",
	    classId: 230101,
	    className: "计算机学院 23 级软件工程 1 班"
	  },
	  {
	    id: 16,
	    studentId: 202303010216,
	    studentName: "何雨薇",
	    status: 2,
	    applyTime: "2025-04-07T09:30:00",
	    startTime: "2025-04-08T09:00:00",
	    endTime: "2025-04-10T14:00:00",
	    message: "参加行业研讨会",
	    teacherId: 101,
	    teacherName: "李建国",
	    classId: 230101,
	    className: "计算机学院 23 级软件工程 1 班"
	  },
	    {
	      id: 101,
	      studentId: 20230021,
	      studentName: "依依",
	      status: 0,
	      applyTime: "2025-04-25T10:15:00",
	      startTime: "2025-04-26T08:00:00",
	      endTime: "2025-04-27T18:00:00",
	      message: "感冒发烧需要休息",
	      teacherId: 1001,
	      teacherName: "王老师",
	      classId: 2301,
	      className: "计算机23级1班"
	    },
	    {
	      id: 102,
	      studentId: 20230022,
	      studentName: "依依",
	      status: 1,
	      applyTime: "2025-04-20T14:30:00",
	      startTime: "2025-04-21T08:00:00",
	      endTime: "2025-04-22T18:00:00",
	      message: "参加编程比赛",
	      teacherId: 1001,
	      teacherName: "王老师",
	      classId: 2301,
	      className: "计算机23级1班"
	    },
	    {
	      id: 103,
	      studentId: 20230023,
	      studentName: "依依",
	      status: 2,
	      applyTime: "2025-04-15T09:45:00",
	      startTime: "2025-04-16T08:00:00",
	      endTime: "2025-04-17T18:00:00",
	      message: "回家探亲",
	      teacherId: 1001,
	      teacherName: "王老师",
	      classId: 2301,
	      className: "计算机23级1班",
	      rejectReason: "非紧急事由不予批准"
	    },
	    {
	      id: 104,
	      studentId: 20230024,
	      studentName: "依依",
	      status: 0,
	      applyTime: "2025-04-24T16:20:00",
	      startTime: "2025-04-25T08:00:00",
	      endTime: "2025-04-26T18:00:00",
	      message: "牙科手术预约",
	      teacherId: 1001,
	      teacherName: "王老师",
	      classId: 2301,
	      className: "计算机23级1班"
	    },
	    {
	      id: 105,
	      studentId: 20230025,
	      studentName: "依依",
	      status: 1,
	      applyTime: "2025-04-18T11:10:00",
	      startTime: "2025-04-19T08:00:00",
	      endTime: "2025-04-20T18:00:00",
	      message: "参加学术会议",
	      teacherId: 1001,
	      teacherName: "王老师",
	      classId: 2301,
	      className: "计算机23级1班"
	    }
	]
	import { teacherSelectByName } from '../../api/sick'
	import { teacherSelectAllsick } from '../../api/sick'
	export default { 
		data () {
			return {
				userInfo: {},
				current: 0,  //切换
				currentTab: 1,
				item: ['待审批','全部申请'],
				searchValue: '', //搜索的学生姓名
				pendingRecordsList: [], //待审批的数据
				allRecordsList: [], //所有状态的数据
				currentpage: 1, // 当前的页码
				size: 5, // 表示当前展示的行数
				total: 0, // 数据总条数
				pages: 1, //总页数
			}
		},
		onShow() {
			this.current = 0  // 回到待审批
			this.currentpage = 1 // 回到第一页
			this.total = 0
			this.checkLoginStatus()
			this.getAllPendinglist()
			this.searchValue = ''
		},
		methods: {
			//模拟的方法
			  // 获取所有待审批请假（status=0）
			  getAllPendingLeaves({ page = 1, size = 5 }) {
			    return new Promise((resolve) => {
			      setTimeout(() => {
			        // 过滤待审批记录
			        const filteredData = mockData.filter(item => item.status === 0)
			        
			        // 计算分页
			        const start = (page - 1) * size
			        const paginatedData = filteredData.slice(start, start + size)
			
			        resolve({
			          code: 200,
			          records: paginatedData,
			          total: filteredData.length,
			          size: size,
			          current: page,
			          pages: Math.ceil(filteredData.length / size)
			        })
			      }, 500)
			    })
			  },
			
			  //按姓名搜索所有状态请假记录
			  searchLeavesByName({ page = 1, size = 5, name = '' }) {
			    return new Promise((resolve) => {
			      setTimeout(() => {
			        // 过滤包含姓名的记录
			        const filteredData = mockData.filter(record => 
			          record.studentName.includes(name)
			        )
			
			        // 分页计算
			        const start = (page - 1) * size
			        const paginatedData = filteredData.slice(start, start + size)
			
			        resolve({
			          code: 200,
			          records: paginatedData,
			          total: filteredData.length,
			          size: size,
			          current: page,
			          pages: Math.ceil(filteredData.length / size)
			        })
			      }, 500)
			    })
			  },
			
			  //按姓名搜索待审批请假（status=0）
			  searchPendingLeavesByName({ page = 1, size = 5, name = '' }) {
			    return new Promise((resolve) => {
			      setTimeout(() => {
			        // 双重过滤：姓名 + 待审批状态
			        const filteredData = mockData.filter(record => 
			          record.studentName.includes(name) && record.status === 0
			        )
			
			        const start = (page - 1) * size
			        const paginatedData = filteredData.slice(start, start + size)
			
			        resolve({
			          code: 200,
			          records: paginatedData,
			          total: filteredData.length,
			          size: size,
			          current: page,
			          pages: Math.ceil(filteredData.length / size)
			        })
			      }, 500)
			    })
			  },
			
			  //获取所有状态请假记录
			  getAllLeaves({ page = 1, size = 5 }) {
			    return new Promise((resolve) => {
			      setTimeout(() => {
			        // 直接使用原始数据
			        const start = (page - 1) * size
			        const paginatedData = mockData.slice(start, start + size)
			
			        resolve({
			          code: 200,
			          records: paginatedData,
			          total: mockData.length,
			          size: size,
			          current: page,
			          pages: Math.ceil(mockData.length / size)
			        })
			      }, 500)
			    })
			},
			
			//-------------------------------------------------------
			  
			// 检查登录状态
			checkLoginStatus() {
				const userInfo = uni.getStorageSync('userInfo')
				if (!userInfo) {
					uni.redirectTo({ url: '/pages/login/login' })
					return
				}
				this.userInfo = {
				    name: userInfo.name,
				    teacherId: userInfo.id || '2023111111111', // 使用模拟数据中的ID
				    role: userInfo.roleName // 新增角色信息
				}
			},
			
			//获取搜索的学生姓名
			search(e){
				this.searchValue = e.value.trim()
				this.current = 0  // 回到待审批
				this.currentpage = 1 // 回到第一页
				this.loadData()
			},
			
			onClickItem(e) {
				if (this.current != e.currentIndex) {
					this.currentpage = 1   //切换的时候，分页的起始页要回到1
					this.current = e.currentIndex
					this.loadData()
			    }
			},
			
			//切换页数
			changepage(e){
				if(e.type === 'next'){
					this.currentpage = e.current;
				}
				if(e.type === 'prev'){
					this.currentpage = e.current;
				}
				this.loadData()
				console.log(this.currentpage)
			},
			
			//点击item跳转到老师审批假条
			ToteacherApproval(item){
				uni.navigateTo({
					url:`/pages/application/teacherApproval?studentApplyInfo=${JSON.stringify(item)}`
				})
			},
			
			//加载数据
			loadData(){
				if(this.current === 0){
					if(this.searchValue.trim() !== ''){
						this.getpendinglistByname({ page: this.currentpage ,size: this.size, name: this.searchValue})
					}else{
						this.getAllPendinglist()
					}
				}else{
					if(this.searchValue.trim() !== ''){
						this.getapplylistByname({ page: this.currentpage ,size: this.size, name: this.searchValue})
					}else{
						this.getAlllist()
					}
				}
			},
						
			//获取待审批的数据
			async getAllPendinglist(){
				uni.showLoading({ title:'加载数据中' })
				try{
					// const res = await teacherSelectAllsick({page: this.currentpage, size: this.size})
					const res = await this.getAllPendingLeaves({page: this.currentpage, size: this.size})
					if(res.code===200){
						uni.showToast({
							title:'获取数据成功',
							icon:'none',
							duration:2000
						})
						this.pendingRecordsList = res.records
						this.total = res.total
						this.pages = res.pages	
					}
				}catch(err){
					uni.showToast({
						title:'获取数据失败',
						icon:'none',
						duration:2000
					})
				}finally{
					uni.hideLoading()
				}
			},
			
			//获取所有状态的数据
			async getAlllist(){
				uni.showLoading({ title:'加载数据中' })
				try{
					const res = await this.getAllLeaves({page: this.currentpage, size: this.size})
					if(res.code===200){
						uni.showToast({
							title:'获取数据成功',
							icon:'none',
							duration:2000
						})
						this.allRecordsList = res.records
						this.total = res.total
						this.pages = res.pages		
					}
				}catch(err){
					uni.showToast({
						title:'获取数据失败',
						icon:'none',
						duration:2000
					})
				}finally{
					uni.hideLoading()
				}
			},
			
			//通过姓名查找学生的待审批假条
			async getpendinglistByname(obj){
				uni.showLoading({ title:'搜索中' })
				try{
					const res = await this.searchPendingLeavesByName(obj)
					if(res.code===200){
						uni.showToast({
							title:'获取数据成功',
							icon:'none',
							duration:2000
						})
						this.pendingRecordsList = res.records
						this.total = res.total
						this.pages = res.pages		
					}
				}catch(err){
					uni.showToast({
						title:'获取数据失败',
						icon:'none',
						duration:2000
					})
				}finally{
					uni.hideLoading()
				}
			},
			
			//通过姓名查找学生的所有假条
			async getapplylistByname(obj){
				uni.showLoading({ title:'搜索中' })
				try{
					// const res = await teacherSelectByName(obj)
					const res = await this.searchLeavesByName(obj)
					if(res.code===200){
						uni.showToast({
							title:'获取数据成功',
							icon:'none',
							duration:2000
						})
						this.allRecordsList = res.records
						this.total = res.total
						this.pages = res.pages		
					}
				}catch(err){
					uni.showToast({
						title:'获取数据失败',
						icon:'none',
						duration:2000
					})
				}finally{
					uni.hideLoading()
				}
			},
			
			switchTab(index) {
			  //this.currentTab = index;
			  
			  // 动态生成路由表
			  const routes = [
			    '/pages/teacher/teacher',
			    '/pages/application/list',
			    '/pages/notification/list',
			    '/pages/user/profile'
			  ];
			  
			  // 添加跳转保护
			  if (index >= routes.length) {
			    uni.showToast({
			      title: '功能正在开发中',
			      icon: 'none'
			    });
			    return;
			  }
			  
			  uni.navigateTo({
			        url: routes[index],
			        success: () => {
			          console.log('路由跳转成功:', routes[index]);
			        },
			        fail: (err) => {
			          console.error('路由跳转失败:', err);
			          uni.showToast({
			            title: '页面加载失败',
			            icon: 'none'
			          });
			        }
			    });
			}
		}
	}
</script>

<style>
	@import url("css/teacherapply.css");
	@import url("../../components/watch-login/css/icon.css");
</style>